package com.liang.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.liang.mall.entity.File;
import com.liang.mall.util.ResultEntity;
import com.liang.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: XIAOLIANG
 * Date: 2021/5/10
 * Time: 16:31
 * Description: No Description
 */
@RestController
@RequestMapping("/file")
public class FileController {


    @Autowired
    FileService fileService;


    /**
     * 文件上传
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("/upload")
//    @PreAuthorize("hasAuthority('sys:oss:all')")
    public ResultEntity upload(MultipartFile file, HttpServletRequest request){


// Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        String accessKeyId = "LTAI5tQCtTouBcgYM4mbeiKC";
        String accessKeySecret = "ZELuNxP8iKvKAEnixOibNc18NItNY2";
        String bucketName = "mall-xiaoliang";
// <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dir = simpleDateFormat.format(new Date())+"/";
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);


            String newFileName= UUID.randomUUID().toString()+"_"+file.getOriginalFilename(); //文件的唯一标识，通常是不重复的文件名

            try {
                PutObjectResult putObjectResult = ossClient.putObject(bucketName, dir + newFileName, file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            File myfile = new File();
            myfile.setFilePath("https://"+bucketName+"."+endpoint+"/"+dir+newFileName);
            Integer adminID = (Integer) request.getSession().getAttribute("adminID");
        myfile.setCreateUser(adminID);
        myfile.setFileOldPath(file.getOriginalFilename());
        myfile.setFileNewName(newFileName);

            boolean save = fileService.save(myfile);
            System.out.println(myfile);
            System.out.println("save = " + save);


        ossClient.shutdown();



// 创建OSSClient实例。

//        https://mall-xiaoliang.oss-cn-beijing.aliyuncs.com/2021-05-10/9775025c-d4db-4341-abfa-85c4510c3433_WinNTSetup_v425%E5%8D%95%E6%96%87%E4%BB%B6%E7%BB%BF%E8%89%B2%E7%89%88_x86_x64.exe
// 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。
//        String content = "Hello OSS";


// 关闭OSSClient。


        //文件 信息入库



        return ResultEntity.ok();

    }

    /**
     * 查询文件列表
      * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
//    @PreAuthorize("hasAuthority('sys:oss:all')")
    public ResultEntity<IPage<File>> getList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize){

     IPage<File> fileIPage =   fileService.getList(pageNum,pageSize);

     return ResultEntity.ok(fileIPage);


    }


    @DeleteMapping("/delete/{id}")
//    @PreAuthorize("hasAuthority('sys:oss:all')")
    public ResultEntity deleteById(@PathVariable("id") Integer id){

        boolean b = fileService.removeById(id);

        if (b){

            return ResultEntity.ok();

        }else {
            return ResultEntity.error("删除失败,文件不存在");
        }

    }

}
